var express = require('express');
var router = express.Router();
var db = require('../../../libs/mysql');

router.get('/',function (req,res) {
    var page = 1; //默认为1
    var num = 10; //一页条数
    if (req.query.page) {
        page = parseInt(req.query.page);
    }
    var count = 0;
    var pages = 0;

    var cateid = req.query.cateid || '';
    db.query(`SELECT * FROM category`,(err,navs)=>{
        if(err){
            res.send('前台分类查询').end();
        }else {
            if(cateid == ''){
                var countsql = 'select count(*) from contents;';
            }else {
                var countsql = 'select count(*) from contents where categoryid='+cateid+';';
            }
            db.query(countsql,(err,count)=>{
                if(err){
                    res.status(500).send('内容总数').end();
                }else {
                    count = count[0]['count(*)'];
                    pages = Math.ceil(count/num);//总页数
                    if(cateid == ''){
                        var sql = 'SELECT u.nickname,c.name,COUNT(p.reviewid),t.* FROM contents t LEFT JOIN user u ON t.userid = u.id LEFT JOIN category c ON t.categoryid = c.id LEFT JOIN comments p on t.id=p.reviewid GROUP BY(t.id) order by id desc limit ' + num + ' offset ' + num * (page - 1);
                    }else {
                        var sql = 'SELECT u.nickname,c.name,COUNT(p.reviewid),t.* FROM contents t LEFT JOIN user u ON t.userid = u.id LEFT JOIN category c ON t.categoryid = c.id LEFT JOIN comments p on t.id=p.reviewid WHERE categoryid='+ cateid +' GROUP BY(t.id) order by id desc limit ' + num + ' offset ' +num * (page-1);
                    }
                    db.query(sql,(err,data)=>{
                        if(err){
                            res.send('内容列表查询').end();
                        }else {
                            res.render('web/index/index', {
                                userInfo:req.userInfo,
                                navs:navs,
                                content:data,
                                count:count,
                                pages:pages,
                                page: page,
                                num:num,
                                cateid:cateid
                            });
                        }
                    })
                }
            });

        }
    })

})

router.use('/log',require('../user/log'));//登录
router.use('/reg',require('../user/reg'));//注册
router.use('/contents',require('../contents/contents'));//内容页

module.exports = router;